// WebSocket连接管理工具
class WebSocketManager {
  constructor() {
    this.connections = new Map()
    this.reconnectAttempts = new Map()
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 5000
    this.userId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  }

  // 创建WebSocket连接
  createConnection(name, url, options = {}) {
    const {
      onOpen = () => {},
      onMessage = () => {},
      onClose = () => {},
      onError = () => {},
      autoReconnect = true,
      maxReconnectAttempts = this.maxReconnectAttempts,
      reconnectInterval = this.reconnectInterval
    } = options

    // 如果连接已存在，先关闭
    if (this.connections.has(name)) {
      this.closeConnection(name)
    }

    try {
      const ws = new WebSocket(url)
      
      // 设置重连参数
      this.reconnectAttempts.set(name, 0)
      
      ws.onopen = (event) => {
        console.log(`WebSocket连接已建立: ${name}`)
        this.reconnectAttempts.set(name, 0)
        onOpen(event)
      }

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          onMessage(data, event)
        } catch (error) {
          console.error(`WebSocket消息解析失败 [${name}]:`, error)
          onMessage(event.data, event)
        }
      }

      ws.onclose = (event) => {
        console.log(`WebSocket连接已关闭: ${name}`)
        onClose(event)
        
        // 自动重连
        if (autoReconnect && this.reconnectAttempts.get(name) < maxReconnectAttempts) {
          const attempts = this.reconnectAttempts.get(name) + 1
          this.reconnectAttempts.set(name, attempts)
          
          console.log(`WebSocket重连中 [${name}] (${attempts}/${maxReconnectAttempts})`)
          setTimeout(() => {
            this.createConnection(name, url, options)
          }, reconnectInterval)
        }
      }

      ws.onerror = (error) => {
        console.error(`WebSocket连接错误 [${name}]:`, error)
        onError(error)
      }

      this.connections.set(name, ws)
      return ws
    } catch (error) {
      console.error(`创建WebSocket连接失败 [${name}]:`, error)
      onError(error)
      return null
    }
  }

  // 关闭WebSocket连接
  closeConnection(name) {
    const ws = this.connections.get(name)
    if (ws) {
      ws.close()
      this.connections.delete(name)
      this.reconnectAttempts.delete(name)
      console.log(`WebSocket连接已关闭: ${name}`)
    }
  }

  // 发送消息
  sendMessage(name, message) {
    const ws = this.connections.get(name)
    if (ws && ws.readyState === WebSocket.OPEN) {
      const data = typeof message === 'string' ? message : JSON.stringify(message)
      ws.send(data)
      return true
    } else {
      console.warn(`WebSocket连接不可用 [${name}]`)
      return false
    }
  }

  // 获取连接状态
  getConnectionState(name) {
    const ws = this.connections.get(name)
    if (!ws) return 'CLOSED'
    
    switch (ws.readyState) {
      case WebSocket.CONNECTING: return 'CONNECTING'
      case WebSocket.OPEN: return 'OPEN'
      case WebSocket.CLOSING: return 'CLOSING'
      case WebSocket.CLOSED: return 'CLOSED'
      default: return 'UNKNOWN'
    }
  }

  // 检查连接是否活跃
  isConnected(name) {
    return this.getConnectionState(name) === 'OPEN'
  }

  // 关闭所有连接
  closeAllConnections() {
    for (const [name] of this.connections) {
      this.closeConnection(name)
    }
  }

  // 获取所有连接名称
  getConnectionNames() {
    return Array.from(this.connections.keys())
  }

  // 创建告警WebSocket连接
  createAlertConnection(baseUrl, options = {}) {
    const {
      onOpen = () => {},
      onMessage = () => {},
      onClose = () => {},
      onError = () => {},
      autoReconnect = true
    } = options

    // 构建告警WebSocket URL
    const wsUrl = `${baseUrl.replace('http', 'ws')}/ws/alerts/${this.userId}`
    
    console.log('🔌 连接告警WebSocket:', wsUrl)
    
    return this.createConnection('alerts', wsUrl, {
      onOpen: (event) => {
        console.log('✅ 告警WebSocket连接已建立')
        // 发送订阅消息
        this.sendMessage('alerts', {
          type: 'subscribe',
          userId: this.userId,
          timestamp: Date.now()
        })
        onOpen(event)
      },
      onMessage: (data, event) => {
        console.log('📨 收到告警WebSocket消息:', data)
        this.handleAlertMessage(data)
        onMessage(data, event)
      },
      onClose: (event) => {
        console.log('❌ 告警WebSocket连接已关闭')
        onClose(event)
      },
      onError: (error) => {
        console.error('🚨 告警WebSocket连接错误:', error)
        onError(error)
      },
      autoReconnect,
      maxReconnectAttempts: this.maxReconnectAttempts,
      reconnectInterval: this.reconnectInterval
    })
  }

  // 处理告警消息
  handleAlertMessage(data) {
    if (!data || typeof data !== 'object') return

    const { type, message, data: payload } = data

    switch (type) {
      case 'connected':
        console.log('✅ WebSocket连接确认:', message)
        break
      case 'new_alert':
        console.log('🚨 收到新告警:', payload)
        this.triggerEvent('newAlert', payload)
        break
      case 'alert_update':
        console.log('🔄 告警状态更新:', payload)
        this.triggerEvent('alertUpdate', payload)
        break
      case 'stats_update':
        console.log('📊 告警统计更新:', payload)
        this.triggerEvent('statsUpdate', payload)
        break
      case 'pong':
        console.log('🏓 收到心跳响应')
        break
      default:
        console.log('❓ 未知消息类型:', type, payload)
    }
  }

  // 触发自定义事件
  triggerEvent(eventName, data) {
    const event = new CustomEvent(eventName, { detail: data })
    window.dispatchEvent(event)
  }

  // 发送心跳
  sendHeartbeat() {
    this.sendMessage('alerts', {
      type: 'ping',
      timestamp: Date.now()
    })
  }

  // 订阅告警推送
  subscribeAlerts() {
    this.sendMessage('alerts', {
      type: 'subscribe',
      userId: this.userId,
      timestamp: Date.now()
    })
  }

  // 取消订阅告警推送
  unsubscribeAlerts() {
    this.sendMessage('alerts', {
      type: 'unsubscribe',
      userId: this.userId,
      timestamp: Date.now()
    })
  }

  // 获取用户ID
  getUserId() {
    return this.userId
  }
}

// 创建全局实例
const wsManager = new WebSocketManager()

export default wsManager
